local t = table();


local json_template = io.handler.json.load("""app:\scripting\library\monitor_postp\json_template.json""");

local generate_array = function(start, step, length)
{
    local result = [];
    for(k,v in 0:length-1)
    {
        local value = start+step*k;
        result.push(value);
    }

    return transpose(result);
}

t.deal_probe_monitor = function(probe_monitor,file_fullpath, dparam, name)
{
    local header = clone(json_template);

    header.result_type = 2;
    header.result_folder_path = "./probe";
    header.result_data_type = 0;
    header.result_data_name_td = name..".csv";
    header.result_data_name_fd="";
    header.time_unit = util.utname(dparam.UT);
    header.time_data = probe_monitor.time_record;
    header.frequency_unit = util.ufname(dparam.UF);
    header.frequency_data = [];
    header.field_monitor_type = 1;
    header.field_monitor_unit = "";
    header.field_monitor_sample_info.sta_x = probe_monitor.pos[0];
    header.field_monitor_sample_info.end_x = "";
    header.field_monitor_sample_info.num_x = "";
    header.field_monitor_sample_info.sta_y = probe_monitor.pos[1];
    header.field_monitor_sample_info.end_y = "";
    header.field_monitor_sample_info.num_y = "";
    header.field_monitor_sample_info.sta_z = probe_monitor.pos[2];
    header.field_monitor_sample_info.end_z = "";
    header.field_monitor_sample_info.num_z = "";
    header.field_monitor_sample_info.sta_theta = "";
    header.field_monitor_sample_info.end_theta = "";
    header.field_monitor_sample_info.num_theta = "";
    header.field_monitor_sample_info.sta_phi = "";
    header.field_monitor_sample_info.end_phi = "";
    header.field_monitor_sample_info.num_phi = "";

    local tmp_data=[];
    tmp_data=cat(1,probe_monitor.time_record,probe_monitor.datas[0]); 
    tmp_data=cat(1, tmp_data,probe_monitor.datas[1]) ;
    tmp_data=cat(1, tmp_data,probe_monitor.datas[2]) ;        

    local first_row = ["# comac datafile version 1.0", "", "",""];
    local second_row = ["# time||"..util.utname(dparam.UT).."||key", "Ex||V/m||value", "Ey||V/m||value", "Ez||V/m||value"];

    local field_data_header = cat(0, first_row, second_row);
    tmp_data = cat(0, field_data_header,tmp_data);

    io.save_csv(file_fullpath..name..".csv", tmp_data);
    
    // local p = io.to_json(header);
    // io.save_txt(file_fullpath..name..".json", p);


    return header;
}

t.deal_plane_monitor = function(plane_monitor, file_fullpath, dparam, name) 
{
    #import pputil;
    local header = clone(json_template);

    header.result_type = 1;
    header.result_folder_path = "";
    header.result_data_type = 1;
    header.result_data_name_td = "";
    header.result_data_name_fd= "";
    header.result_data_folder_name_td="";
    header.result_data_folder_name_fd= "plane";
    header.time_unit = "";
    header.time_data = [];
    header.frequency_unit = util.ufname(dparam.UF);
    header.frequency_data = plane_monitor.freq;
    header.field_monitor_type = 2;
    header.field_monitor_unit = "";


    local adjust = pputil.slicedata.adjust;
    Slice_F_single=function(m,index,Eflag,flag,nu,nv,coorduv)
    {
        if(is_nil(index))
        {index=0;}// 指定第0个频点
        local array_data=[];
        local data,plane,freq,pos_user,coord,range0,num;
        if(numel(Eflag)==2 && Eflag[0]!='S')
        {
            data = m.data[index];     // 取出数据
            plane = m.coord.plane;
            freq=m.freq[index];
            pos_user=m.coord.pos_user;
            coord=m.coord;
        }else if (Eflag[0]=='S')
        {
            data = m.Sdata[index];     // 取出数据
            plane = m.Eu.coord.plane;
            freq=m.freq[index];
            coord=m.Eu.coord;
            pos_user=m.Eu.coord.pos_user;
        }else
        {
            logger.log_message("This Eflag :%s not correct",Eflag)
            return 0;
        }
        data = adjust(data, plane); // 调整数据维度到局部坐标系排列方式

        local cs = [coord.x, coord.y, coord.z];
        local ucoord0 = cs[(plane+1)%3];
        local vcoord0 = cs[(plane+2)%3];
        local info=["X","Y","Z"][(plane+1)%3]..["X","Y","Z"][(plane+2)%3];
        if (plane==1)  //zox平面 调整为 xoz
        {
            data = transpose(data);
            ucoord0 = cs[0];
            vcoord0 = cs[2];
            info ="XZ";
        }
        local umin = min(ucoord0);
        local umax = max(ucoord0);
        local vmin = min(vcoord0);
        local vmax = max(vcoord0);
        //local nu = 201; // 指定u方向重采样的点数
        //local nv = 201; // 指定u方向重采样的点数
        local ret=table()
        if(flag)
        {
            local us = linspace(umin, umax, nu);
            local vs = linspace(vmin, vmax, nv);
            if(!is_nil(coorduv))
            {
                us=coorduv[0];
                vs=coorduv[1];
            }
            local data1 = math.interp2(ucoord0, vcoord0, data)(us, vs);
            ret.uc=clone(us);
            ret.vc=clone(vs);
            //ret.rdata=real(data1);
            //ret.idata=imag(data1);
            array_data=data1;
        }else
        {
            ret.uc=clone(ucoord0);
            ret.vc=clone(vcoord0);
            array_data=data;
        }
        ret.freq=freq;
        ret.data=array_data;
        ret.info=info;
        ret.Edir=Eflag;
        ret.plane=plane;
        ret.pos_user=pos_user;
        if(plane==0) //YOZ
        {
            range0=[pos_user,min(ret.uc),min(ret.vc),pos_user,max(ret.uc),max(ret.vc)];
            num=[1,numel(ret.uc),numel(ret.vc)];
        
        }else if(plane==1) //ZOX
        {
            range0=[min(ret.uc),pos_user,min(ret.vc),max(ret.uc),pos_user,max(ret.vc)];
            num=[numel(ret.uc),1,numel(ret.vc)];
        }else  //XOY
        {
            range0=[min(ret.uc),min(ret.vc),pos_user,max(ret.uc),max(ret.vc),pos_user];
            num=[numel(ret.uc),numel(ret.vc),1];
        }
        ret.pos=range0;
        ret.num=num;
        return ret;
    };

    local Eflag=plane_monitor.field_expr;
    local freqs = plane_monitor.freq;
    local plane,nu,nv,uc,vc,num,pos_user,pos,sample_info,user_coord;  //如果需要指定nv,nu (u轴,v轴坐标数量)
    local tmp_data=[];
    local first_row;
    local second_row;
    for(local index=0;index<numel(freqs);index++)
    {

        if(numel(Eflag)==2)// 单分量处理 输出是单个量的表 tmp_data 表定义见Slice_F_single 返回值
        {
            tmp_data = Slice_F_single(plane_monitor,index,Eflag);
            uc =tmp_data.uc;
            vc = tmp_data.vc;
            plane = tmp_data.plane;
            nu=numel(uc);
            nv=numel(vc); 
            local info =tmp_data.info;
            first_row = ["# comac datafile version 1.0","","",""];   
            second_row= ["# "..info[0].."||"..util.ulname(dparam.UL).."||key",info[1].."||"..util.ulname(dparam.UL).."||key","Re("..tmp_data.Edir..")||V/m||value","Im("..tmp_data.Edir..")||V/m||value"];
            pos=tmp_data.pos;
            num=tmp_data.num;

        }
        else if(Eflag=="EVec"||Eflag=="HVec"||Eflag=="EVec&HVec") //处理矢量  输出是个多个量的数组表tmp_data， 表定义见Slice_F_single 返回值
        {
            local coordx,coordy,coordz,coorduv;
            if(Eflag="EVec"||Eflag =="Evec&Hvec"||Eflag=="EVec&HVec")
            {
                coordx = plane_monitor.Ex.coord;
                coordy = plane_monitor.Ey.coord;
                coordz = plane_monitor.Ez.coord;
                plane =  plane_monitor.Ex.coord.plane;
                pos_user= plane_monitor.Ex.coord.pos_user
            }else
            {
                coordx = plane_monitor.Hx.coord;
                coordy = plane_monitor.Hy.coord;
                coordz = plane_monitor.Hz.coord;
                plane = plane_monitor.Hx.coord.plane;
                pos_user=plane_monitor.Hx.cooord.pos_user;
            }
            local tmp_x = unique(sort(cat(0,coordx.x,coordy.x,coordz.x)));  
            local tmp_y = unique(sort(cat(0,coordx.y,coordy.y,coordz.y)));
            local tmp_z = unique(sort(cat(0,coordx.z,coordy.z,coordz.z)));
            local numx = max(numel(coordx.x),numel(coordy.x),numel(coordz.x)); //目的统一一个维度的数据大小
            local numy = max(numel(coordx.y),numel(coordy.y),numel(coordz.y));
            local numz = max(numel(coordx.z),numel(coordz.z),numel(coordz.z));
            local nu1=?(numx==1,numy,numx);
            local nv1=?(numz==1,numy,numz);
            if(!is_nil(nu))
            {
                nu1= nu;
            }
            if(!is_nil(nv))
            {
                nv1= nv;
            }
            local range;
            if(!is_nil(user_coord))
            {
                range = user_coord;
            }else
            {
                range =[tmp_x[0],tmp_y[0],tmp_z[0],tmp_x[end],tmp_y[end],tmp_z[end]];
            }
            local ucoord1,vcoord1;
            if(plane==0)  //2 xoy 1 zox 0 yoz
            {
                ucoord1 = linspace(range[1],range[4],nu1); //y
                vcoord1 = linspace(range[2],range[5],nv1); //z
                range[0]=pos_user;
                range[3]=pos_user;

            }else if(plane==1)
            {
                ucoord1 = linspace(range[0],range[3],nu1);//x
                vcoord1 = linspace(range[2],range[5],nv1); //z
                range[1]=pos_user;
                range[4]=pos_user;
            }else
            {
                ucoord1 = linspace(range[0],range[3],nu1);//x
                vcoord1 = linspace(range[1],range[4],nv1); //y
                range[2]=pos_user;
                range[5]=pos_user;
            }
            pos=range;
            num=[numx,numy,numz];
            coorduv=pack(ucoord1,vcoord1);
            
            if (Eflag=="EVec")
            {
                local Ex=Slice_F_single(plane_monitor.Ex,index,"Ex",1,nu1,nv1,coorduv);
                local Ey=Slice_F_single(plane_monitor.Ey,index,"Ey",1,nu1,nv1,coorduv);
                local Ez=Slice_F_single(plane_monitor.Ez,index,"Ez",1,nu1,nv1,coorduv);
                tmp_data= pack(Ex,Ey,Ez);
                local info=Ex.info;
                first_row = ["# comac datafile version 1.0","","","","","","",""];
                second_row =["# "..info[0].."||"..util.ulname(dparam.UL).."||key",info[1].."||"..util.ulname(dparam.UL).."||key","Re(Ex)||V/m||value","Im(Ex)||V/m||value",
                "Re(Ey)||V/m||value","Im(Ey)||V/m||value","Re(Ez)||V/m||value","Im(Ez)||V/m||value"];
                
            }else if(Eflag=="HVec")
            {   
                local Hx=Slice_F_single(plane_monitor.Hx,index,"Hx",1,nu1,nv1,coorduv);
                local Hy=Slice_F_single(plane_monitor.Hy,index,"Hy",1,nu1,nv1,coorduv);
                local Hz=Slice_F_single(plane_monitor.Hz,index,"Hz",1,nu1,nv1,coorduv);
                tmp_data= pack(Hx,Hy,Hz);
                local info = Hx.info;
                first_row = ["# comac datafile version 1.0","","","","","","",""];
                second_row = ["# "..info[0].."||"..util.ulname(dparam.UL).."||key",info[1].."||"..util.ulname(dparam.UL).."||key","Re(Hx)||V/m||value","Im(Hx)||V/m||value",
                "Re(Hy)||V/m||value","Im(Hy)||V/m||value","Re(Hz)||V/m||value","Im(Hz)||V/m||value"];
            }else
            {
                local Ex=Slice_F_single(plane_monitor.Ex,index,"Ex",1,nu1,nv1,coorduv);
                local Ey=Slice_F_single(plane_monitor.Ey,index,"Ey",1,nu1,nv1,coorduv);
                local Ez=Slice_F_single(plane_monitor.Ez,index,"Ez",1,nu1,nv1,coorduv);
                local Hx=Slice_F_single(plane_monitor.Hx,index,"Hx",1,nu1,nv1,coorduv);
                local Hy=Slice_F_single(plane_monitor.Hy,index,"Hy",1,nu1,nv1,coorduv);
                local Hz=Slice_F_single(plane_monitor.Hz,index,"Hz",1,nu1,nv1,coorduv);
                tmp_data=pack(Ex,Ey,Ez,Hx,Hy,Hz);
                local info = Hx.info;
                first_row = ["# comac datafile version 1.0","","","","","","","","","","","","",""];
                second_row = ["# "..info[0].."||"..util.ulname(dparam.UL).."||key",info[1].."||"..util.ulname(dparam.UL).."||key","Re(Ex)||V/m||value","Im(Ex)||V/m||value",
                "Re(Ey)||V/m||value","Im(Ey)||V/m||value","Re(Ez)||V/m||value","Im(Ez)||V/m||value","Re(Hx)||V/m||value","Im(Hx)||V/m||value",
                "Re(Hy)||V/m||value","Im(Hy)||V/m||value","Re(Hz)||V/m||value","Im(Hz)||V/m||value"];
            }
        }
        //单次对抽出的数据进行保存处理（监视器一个频点保存一次）
        local U_c,V_c,data;
        if(is_table(tmp_data))
        {
            U_c,V_c=math.ndgrid(tmp_data.uc,tmp_data.vc);
            local data0 =tmp_data.data;
            data=cat(1,U_c[:],V_c[:],real(data0[:]),imag(data0[:]));   
        }else if(is_array(tmp_data))
        {
            U_c,V_c=math.ndgrid(tmp_data[0].uc,tmp_data[0].vc);
            
            local data0=cat(1,U_c[:],V_c[:]);
            for_each(v in tmp_data)
            {
                data0=cat(1,data0,real(v.data[:]),imag(v.data[:]));
            };
            data=data0;
        }
        local fn=fs.makepath(string.format(name.."_%03d.csv", index), file_fullpath)
        local field_data_header = cat(0, first_row, second_row);
        data = cat(0, field_data_header,data);
        io.save_csv(fn,data)
    }
    //循环结束后对写json文件

    header.field_monitor_sample_info.sta_x = pos[0];
    header.field_monitor_sample_info.end_x = pos[3];
    header.field_monitor_sample_info.num_x = num[0];
    header.field_monitor_sample_info.sta_y = pos[1];
    header.field_monitor_sample_info.end_y = pos[4];
    header.field_monitor_sample_info.num_y = num[1];
    header.field_monitor_sample_info.sta_z = pos[2];
    header.field_monitor_sample_info.end_z = pos[5];
    header.field_monitor_sample_info.num_z = pos[2];
    header.field_unit = table{
        coordinate: util.ulname(dparam.UL);
        E_field: "V/m";
        H_field: "A/m";
        frequency: util.ufname(dparam.UF);
        time: util.utname(dparam.UT)
    }



    //  local header = table();
    //  header.datafile_type = "csv";
    // header.unit = table
    // {
    //     coordinate : util.ulname(dparam.UL);
    //     E_field    : "V/m";
    //     H_field    : "A/m";
    //     frequency  : util.ufname(dparam.UF);
    //     time : util.utname(dparam.UT)
    // };
    // header.Domain_info = "FREQ_DOMAIN";
    // header.field_monitor_type="cartesian_surface";
    // sample_info=table{
    //             sta_x:pos[0];
    //             end_x:pos[3];;
    //             num_x:num[0];
    //             sta_y:pos[1];
    //             end_y:pos[4];;
    //             num_y:num[1];
    //             sta_z:pos[2];
    //             end_z:pos[5];
    //             num_z:num[2];
    //         };
    // header.field_monitor_sample_info=sample_info;
    // header.field_monitor_name=name;
    // header.field_monitor_freq=freqs;
    // local p = io.to_json(header);     //注意json保存名称和位置
    // io.save_txt(file_fullpath..name..".json", p);

    return header;
}


t.deal_cable_voltage_monitor = function(cable_monitor, file_fullpath, dparam,name)
{

    local header = clone(json_template);

    local V=cable_monitor.data;
    local Time_record=cable_monitor.time_record;
    
    local dt=Time_record.dt;
    local tmin=Time_record.t0;
    local tmax=dt*(length(V)-1);
    local ts=transpose(linspace(tmin,tmax,length(V)));
    local R=50;
    local I=V/R;
    local fn=fs.makepath(name.."_Voltage.csv", file_fullpath);
    logger.log_message("Write_file: %s", fn);
    local tmp_data=[];
    local first_row = ["# comac datafile version 1.0", ""];
    local second_row = ["# time||"..util.utname(dparam.UT).."||key", name.."_voltage||V||value"];
    tmp_data=cat(1,ts[:],V);          
    local save_data= cat(0,first_row,second_row,tmp_data);
    fn=fs.makepath(name.."_Voltage.csv", file_fullpath);
    logger.log_message("Write_file: %s", fn);
    io.save_csv(fn,save_data);
    
    // tmp_data=[];
    // title=[];
    // second_row = ["# time||"..util.utname(dparam.UT).."||key", name.."__current||A||value"];
    // tmp_data=cat(1,ts[:],I);
    // save_data=cat(0,first_row,second_row,tmp_data);
    // fn=fs.makepath(name.."_Electric.csv", cable_electric_path);         
    // logger.log_message("Write_file: %s", fn);
    // io.save_csv(fn,save_data);

    header.result_type = 10;
    header.result_folder_path = "";
    header.result_data_type = 0;
    header.result_data_name_td = "";
    header.result_data_name_fd="";
    header.result_data_folder_name_td = "cable_voltage";
    header.result_data_folder_name_fd = "";
    header.time_unit = util.utname(dparam.UT);
    header.time_data = ts;
    header.frequency_unit = util.ufname(dparam.UF);
    header.frequency_data = [];
    header.field_monitor_type = "";
    header.field_monitor_unit = "";

    header.field_monitor_sample_info.sta_x = "";
    header.field_monitor_sample_info.end_x = "";
    header.field_monitor_sample_info.num_x = "";
    header.field_monitor_sample_info.sta_y = "";
    header.field_monitor_sample_info.end_y = "";
    header.field_monitor_sample_info.num_y = "";
    header.field_monitor_sample_info.sta_z = "";
    header.field_monitor_sample_info.end_z = "";
    header.field_monitor_sample_info.num_z = "";
    header.field_monitor_sample_info.sta_theta = "";
    header.field_monitor_sample_info.end_theta = "";
    header.field_monitor_sample_info.num_theta = "";
    header.field_monitor_sample_info.sta_phi = "";
    header.field_monitor_sample_info.end_phi = "";
    header.field_monitor_sample_info.num_phi = "";
    // local p = io.to_json(header);
    // io.save_txt(file_fullpath..name..".json", p);

    return header;
}

t.deal_cable_current_monitor = function(cable_monitor, file_fullpath, dparam,name)
{

    local header = clone(json_template);


    local V=cable_monitor.data;
    local Time_record=cable_monitor.time_record;
    
    local dt=Time_record.dt;
    local tmin=Time_record.t0;
    local tmax=dt*(length(V)-1);
    local ts=transpose(linspace(tmin,tmax,length(V)));
    local R=50;
    local I=V/R;
    local fn=fs.makepath(name.."_Current.csv", file_fullpath);
    logger.log_message("Write_file: %s", fn);
    local tmp_data=[];
    local first_row = ["# comac datafile version 1.0", ""];
    // local second_row = ["# time||"..util.utname(dparam.UT).."||key", name.."_voltage||V||value"];
    // tmp_data=cat(1,ts[:],V);          
    // local save_data= cat(0,first_row,second_row,tmp_data);
    // fn=fs.makepath(name.."_Current.csv", cable_current_path);
    // logger.log_message("Write_file: %s", fn);
    // io.save_csv(fn,save_data);
    
    tmp_data=[];
    title=[];
    second_row = ["# time||"..util.utname(dparam.UT).."||key", name.."__current||A||value"];
    tmp_data=cat(1,ts[:],I);
    save_data=cat(0,first_row,second_row,tmp_data);
    fn=fs.makepath(name.."_Current.csv", file_fullpath);         
    logger.log_message("Write_file: %s", fn);
    io.save_csv(fn,save_data);

    header.result_type = 11;
    header.result_folder_path = "";
    header.result_data_type = 0;
    header.result_data_name_td = "";
    header.result_data_name_fd="";
    header.result_data_folder_name_td = "cable_current";
    header.result_data_folder_name_fd = "";
    header.time_unit = util.utname(dparam.UT);
    header.time_data = ts;
    header.frequency_unit = util.ufname(dparam.UF);
    header.frequency_data = [];
    header.field_monitor_type = "";
    header.field_monitor_unit = "";

    header.field_monitor_sample_info.sta_x = "";
    header.field_monitor_sample_info.end_x = "";
    header.field_monitor_sample_info.num_x = "";
    header.field_monitor_sample_info.sta_y = "";
    header.field_monitor_sample_info.end_y = "";
    header.field_monitor_sample_info.num_y = "";
    header.field_monitor_sample_info.sta_z = "";
    header.field_monitor_sample_info.end_z = "";
    header.field_monitor_sample_info.num_z = "";
    header.field_monitor_sample_info.sta_theta = "";
    header.field_monitor_sample_info.end_theta = "";
    header.field_monitor_sample_info.num_theta = "";
    header.field_monitor_sample_info.sta_phi = "";
    header.field_monitor_sample_info.end_phi = "";
    header.field_monitor_sample_info.num_phi = "";
    // local p = io.to_json(header);
    // io.save_txt(file_fullpath..name..".json", p);

    return header;
}


t.deal_lumped_port = function(lumped_port, file_fullpath, dparam, name)
{
    local header = clone(json_template);

    header.result_type = 10;
    header.result_folder_path = "./lumped_port";
    header.result_data_type = 0;
    header.result_data_name_td = name..".csv";
    header.result_data_name_fd = "";
    header.time_unit = util.utname(dparam.UT);
    header.time_data = [];
    header.frequency_unit = util.ufname(dparam.UF);
    header.frequency_data = [];
    header.field_monitor_type = "";
    header.field_monitor_unit = "";

    header.field_monitor_sample_info.sta_x = "";
    header.field_monitor_sample_info.end_x = "";
    header.field_monitor_sample_info.num_x = "";
    header.field_monitor_sample_info.sta_y = "";
    header.field_monitor_sample_info.end_y = "";
    header.field_monitor_sample_info.num_y = "";
    header.field_monitor_sample_info.sta_z = "";
    header.field_monitor_sample_info.end_z = "";
    header.field_monitor_sample_info.num_z = "";
    header.field_monitor_sample_info.sta_theta = "";
    header.field_monitor_sample_info.end_theta = "";
    header.field_monitor_sample_info.num_theta = "";
    header.field_monitor_sample_info.sta_phi = "";
    header.field_monitor_sample_info.end_phi = "";
    header.field_monitor_sample_info.num_phi = "";

    local V_data = lumped_port.V_by_time.data;
    local delta_t = dparam.delta_t;
    local time_array = generate_array(0, delta_t, length(V_data));

    local fn=fs.makepath(name.."_Voltage.csv", file_fullpath);
    logger.log_message("Write_file: %s", fn);


    local tmp_data=[];
    local first_row = ["# comac datafile version 1.0", ""];
    local second_row = ["# time||"..util.utname(dparam.UT).."||key", name.."_voltage||V||value"];

    tmp_data=cat(1, time_array,V_data);  
    
    local save_data= cat(0,first_row,second_row,tmp_data);
    fn=fs.makepath(name..".csv", file_fullpath);
    logger.log_message("Write_file: %s", fn);
    io.save_csv(fn,save_data);
    

    // local p = io.to_json(header);
    // io.save_txt(file_fullpath..name..".json", p);

    return header;
}

return t;

/*----------------以下为调试用代码----------

path="D:/"
deal_probe_monitor(probe_1[0],path,dparam,"probe_1")

deal_plane_monitor(xoy1[0],path,dparam,"xoy1")
/deal_plane_monitor(xoy1_2[0],path,dparam,"xoy1_2")
deal_cable_monitor(cable0[0],path,dparam,"cable")


*/